import { request } from "../../utils/request"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {}, //收货地址
    orderItemList: [], //订单项
    count: 0, //总数量
    total: 0, //订单总价
    orderToken: "", //订单令牌
    requestParam: { //生成订单的请求参数
      orderType: "", //订单类型 0购物车 1立即购买
      productId: 0 //商品id
    }
  },

  /**
   * 处理收货地址选择事件
   */
  handlerAddressChoose() {
    //获取全局app对象
    const app = getApp()
    //将全局索引设置为0,代表是从“订单”里点击进入的收货地址
    app.globalData.addressIndex = 0
    //跳转到地址选择页
    wx.navigateTo({
      url: "/pages/address/address"
    })
  },

  /**
   * 加载订单确认数据
   */
  async loadOrderConfrim() {
    const { token } = wx.getStorageSync("user")
    const res = await request({ url: "/order/getAckOrderInfo/", method: "POST", header: { "Authorization": token }, data: this.data.requestParam })
    if (res.data.state === 0) {
      const data = res.data.data
      this.setData({
        address: data.address,
        orderItemList: data.orderItemList,
        count: data.count,
        total: data.total,
        orderToken: data.orderToken
      })
    }

  },

  /**
   * 提交订单
   */
  submitOrder() {
    //构建请求参数
    const requestData = {
      addressId: this.data.address.id,
      orderItems: this.data.orderItemList,
      total: this.data.total,
      orderToken: this.data.orderToken,
      orderType: this.data.requestParam.orderType
    }
    const { token } = wx.getStorageSync("user")
    //提交订单
    request({ url: "/order/submitOrder/", method: "POST", data: requestData, header: { "Authorization": token } }).then(res1 => {
      if (res1.data.state === 0) {
        //生成微信支付的预付单
        request({ url: "/pay/generateAdvancedOrder/", method: "POST", data: res1.data.data, header: { "Authorization": token } }).then(res2 => {
            console.log(res2)
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const requestParam = {
      orderType: options.orderType,
      productId: options.productId
    }
    this.setData({ requestParam })
    this.loadOrderConfrim()
  }
})